package com.my.fo.strategy.util;

import com.my.fo.strategy.interfaces.StrategyFactoryName;
import com.my.fo.util.ClassUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class StrategyMapUtil {

    public static <T> Map<String, T> getStrategyMap(String packageName, boolean isRecursion) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Set<String> classNameSet = ClassUtils.getClassName(packageName, isRecursion);
        Map<String, T> strategyMap = new HashMap<>();
        for (String className : classNameSet) {
            Class<T> aClass = (Class<T>) Class.forName(className);
            T object = aClass.getDeclaredConstructor().newInstance();
            StrategyFactoryName strategyFactoryName = object.getClass().getAnnotation(StrategyFactoryName.class);
            if (strategyFactoryName == null) continue;
            strategyMap.put(strategyFactoryName.value(), object);
        }
        return strategyMap;
    }

}
